<template>
  <div>
    <el-card>
      <el-form label-width="120px" ref="formDom" :rules="dataRules" :model="dataForm">
        <el-form-item label="spu名称" prop="spuName" size="small" class="input">
          <el-input v-model="dataForm.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="tmId" size="small">
          <el-select placeholder="选择" v-model="dataForm.tmId">
            <el-option
              v-for="(item, index) in tradeMarkSelect"
              :key="index"
              :label="item.tmName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌描述" prop="description" size="mini ">
          <el-input
            type="textarea"
            class="textarea"
            placeHolder="请输入品牌描述"
            v-model="dataForm.description"
            rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="spu图片" prop="spuImageList">
          <el-upload
            :file-list="spuImageList2"
            action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="uploadImg"
            :on-exceed="handleUploadExceed"
            :limit="3"
          >
            <i class="el-icon-plus"></i>

            <template #tip>
              <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
            </template>
          </el-upload>
          <!-- <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog> -->
        </el-form-item>
        <el-form-item label="销售属性" prop="spuSaleAttrList" size="small">
          <el-select :placeholder="attrSaleShow.length ? '选择' : '没有啦!'" v-model="attrSaleId">
            <el-option
              v-for="item in attrSaleShow"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button type="primary" @click="attrSaleADD" :disabled="!attrSaleId"
            >添加销售属性</el-button
          >
        </el-form-item>
        <el-table :data="dataForm.spuSaleAttrList" style="width: 100%">
          <el-table-column align="center" label="序号" width="80" type="index"> </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180"> </el-table-column>
          <el-table-column prop="address" label="属性值名称">
            <template v-slot="{ row }">
              <div class="wrap">
                <div v-if="!row.isEdit">
                  <el-tag
                    closable
                    :type="''"
                    class="tag"
                    v-for="(item, index) in row.spuSaleAttrValueList"
                    :key="index"
                    @close="deleteTag(row.spuSaleAttrValueList, item)"
                  >
                    {{ item.saleAttrValueName }}
                  </el-tag>
                  <el-button size="mini" class="button" @click="goInput(row)">
                    <i class="el-icon-plus icon"></i>
                  </el-button>
                </div>
                <el-input
                  v-else
                  ref="input"
                  @blur="addAttrValueList(row)"
                  v-model="inputValue"
                  size="mini"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template v-slot="{ row }">
              <el-button
                type="danger"
                size="mini"
                class="button"
                @click="deleteAttr(row.baseSaleAttrId)"
              >
                <i class="el-icon-delete icon"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button size="small" type="primary" @click="saveAttrSale"
            >保存{{ addOrEdit == 1 ? '添加' : '修改' }}</el-button
          >
          <el-button size="small" @click="$emit('toggle', 0)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import store from '@/store'
import { mapActions, mapState } from 'vuex'
// tradeMarkSelect
export default {
  name: 'AddOrEditSpu',
  props: ['addOrEdit'],
  data() {
    // console.log(this.$store.state.attr.category3Id)
    const category3Id = this.$store.state.attr.category3Id
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      tradeMark: '',
      colorTypeSize: '',
      spuImageList2: [],
      saleList: [],
      isAddAttrValue: false,
      dataForm: {
        category3Id,
        description: '',
        spuImageList: [
          // {
          //   id: 0,
          //   imgName: 'string',
          //   imgUrl: 'string',
          //   spuId: 0
          // }
        ],
        spuName: '',
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: 'string',
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: 'string',
          //       saleAttrName: 'string',
          //       saleAttrValueName: 'string',
          //       spuId: 0
          //     }
          //   ]
          // }
        ],

        tmId: ''
      },
      attrSaleId: '',
      inputValue: '',
      dataRules: {
        spuName: [
          {
            required: true,
            message: '请输入spu名称',
            trigger: 'blur'
          }
        ],
        tmId: [
          {
            required: true,
            message: '请选择品牌',
            trigger: 'change'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入spu描述',
            trigger: 'blur'
          }
        ],
        spuImageList: [
          {
            required: true,
            message: '请选择一张图片',
            trigger: 'blur'
          }
        ],
        spuSaleAttrList: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value.length) {
                callback(new Error('请至少添加一个销售属性'))
                return
              }
              // 每个销售属性至少添加一个属性值
              if (value.some(spuSaleAttr => !spuSaleAttr.spuSaleAttrValueList.length)) {
                callback(new Error('每个销售属性至少添加一个属性值'))
                return
              }
              // 一定要调用，校验通过
              callback()
            }
          }
        ]
      }
    }
  },
  async beforeMount() {
    try {
      // console.log(this.category3Id, this.getTradeMarkSelect, this.getBaseSaleAttrList)
      //获取品牌数据和销售属性数据
      await this.getTradeMarkSelect(this.category3Id)
      if (this.addOrEdit === 1) {
        const result = await this.getBaseSaleAttrList()
        this.saleList = result
      } else {
        const spuId = this.$store.state.spu.spuId
        await this.getSpuImageList(spuId)
        await this.getSpuInfo(spuId)
        // console.log(this.spuImageList)
        // console.log(this.spuInfo)
        var imgs = this.spuImageList.map((item, index) => {
          return { name: item.imgName, url: item.imgUrl }
        })
        this.spuInfo.spuImageList = this.spuImageList
        this.spuInfo.spuSaleAttrList.forEach(item => {
          this.$set(item, 'isEdit', false)
        })
        console.log('@@', this.spuInfo)
        // console.log('@@', imgs)

        this.dataForm = this.spuInfo
        this.spuImageList2 = imgs
      }
    } catch (error) {
      console.log(error)
    }
  },
  methods: {
    ...mapActions('spu', [
      'getTradeMarkSelect',
      'getBaseSaleAttrList',
      'AddSpu',
      'updateSpu',
      'getSpuImageList',
      'getSpuInfo'
    ]),
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    uploadImg(response, file, fileList) {
      // 上传成功时fileList中的response的data保存着图片地址
      // console.log(response, file, fileList)

      try {
        this.dataForm.spuImageList = fileList.map((item, index) => {
          if (item.response) {
            return { imgUrl: item.response.data, imgName: index + 1 + '.jpg' }
          } else {
            return { imgUrl: item.url, imgName: item.name }
          }
        })

        this.$refs.formDom.validate()
      } catch (error) {
        console.log(error)
      }
    },
    attrSaleADD() {
      var obj = this.saleAttrList.filter(item => {
        return this.attrSaleId == item.id
      })
      var obj2 = {
        baseSaleAttrId: obj[0].id,
        isEdit: false,
        saleAttrName: obj[0].name,
        spuSaleAttrValueList: []
      }
      // this.$set(this.goodsdata, 'isShow', false)
      this.dataForm.spuSaleAttrList.push(obj2)
      this.attrSaleId = null
    },
    deleteAttr(id) {
      var index = this.dataForm.spuSaleAttrList.findIndex(item => {
        return id == item.id
      })
      this.dataForm.spuSaleAttrList.splice(index, 1)
    },
    goInput(row) {
      row.isEdit = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    //input失去焦点添加tag
    addAttrValueList(row) {
      row.isEdit = false
      if (!this.inputValue) return
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: this.inputValue
      })
      this.inputValue = ''
      try {
        this.$refs.formDom.validate()
      } catch (error) {}
    },
    beforeAvatarUpload(file) {
      // console.log(file)
      const isJPG = file.type === 'image/jpeg' || file.type == 'png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async saveAttrSale() {
      // var obj={...}

      try {
        await this.$refs.formDom.validate()
        var arr = this.dataForm.spuSaleAttrList.map(item => {
          delete item.isEdit
          return { ...item }
        })
        var obj = { ...this.dataForm }
        //addOrEdit是1的时候执行添加，2的时候执行修改
        if (this.addOrEdit == 1) {
          console.log(obj)
          await this.AddSpu(obj)
          this.$message.success('添加spu成功!!')
        } else {
          await this.updateSpu(obj)
          this.$message.success('修改spu成功!!')
        }

        this.$emit('toggle', 0)
      } catch (error) {
        console.log(error)
      }
    },
    handleUploadExceed() {
      this.$message.error('最多上传3张图片哦!!')
    },
    deleteTag(list, row) {
      let index = list.findIndex(item => {
        return item.id == row.id
      })
      list.splice(index, 1)
    }
  },
  computed: {
    ...mapState({
      category3Id: state => {
        return state.attr.category3Id
      },
      tradeMarkSelect: state => state.spu.tradeMarkSelect,
      saleAttrList: state => state.spu.saleAttrList,
      spuImageList: state => state.spu.spuImageList,
      spuInfo: state => state.spu.spuInfo
    }),
    //根据添加的销售属性，过滤掉选择框要展示的数据
    attrSaleShow() {
      var idList = []
      this.dataForm.spuSaleAttrList.forEach(item => {
        idList.push(item.baseSaleAttrId)
      })
      return this.saleAttrList.filter(item => {
        return !idList.includes(item.id)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// .textarea {
//   height: 500px;
// }
.wrap {
  height: 30px;
}
.tag {
  margin-right: 10px;
}
</style>
